package com.bci.common;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; 
public class SafeUtil {

	/***
	 * 判断是否纯数字
	 * ***/
	public static boolean isNumeric(String str) {
		boolean flag = true;
		if (str.length() == 0) {
			flag = false;
		} else {
			for (int i = str.length(); --i >= 0;) {
				if (!Character.isDigit(str.charAt(i))) {
					flag = false;
				}
			}
		}
		return flag;
	}

	/***
	 * 是否安全判断 此方法仅判断是否适合安全的插入到数据库 lijinyang 20091016 *
	 **/
	public static boolean isSafe4Db(String o) {
		boolean isSafe = false;
		String temp = "";
		temp = sql_inj(o);
		if (temp.equals(o)) {
			isSafe = true; // 过滤前后字符串无变化的就是安全的字符串
		}
		return isSafe;

	}

	/*
	 * XSS跨站脚本注入过滤 Lijinyang 20090723
	 */
	public static String xss_inj(String str) {
		String safeString = str;
		if (safeString == null) {
			safeString = "";
		}
		safeString = safeString.replaceAll("&", "&#x26;");
		safeString = safeString.replaceAll("<", "&#x3C;");
		safeString = safeString.replaceAll(">", "&#x3E;");
		safeString = safeString.replaceAll("javascript:", "javascript：");
		safeString = safeString.replaceAll("jscript:", "jscript：");
		safeString = safeString.replaceAll("vbscript", "vbscript：");
		safeString = safeString.replaceAll("	", "&nbsp;&nbsp;");
		safeString = safeString.replaceAll(" ", "&nbsp;");
		safeString = safeString.replaceAll("/\\*\\*/", "注释:");

		return safeString;
	}

	/*
	 * SQL注入过滤 从表单获取的数据再传入到数据库前一定要做过滤，避免被恶意攻击 Lijinyang 20090307 20090730 增加过滤0x
	 * Lijinyang 去除 - 的过滤
	 */
	public static String sql_inj(String str) {
		String safeString = str;
		if (safeString == null) {
			safeString = "";
		}
		String inj_str = "'|and|exec|insert|select|delete|update|count|\\*|%|chr|mid|master|truncate|char|declare|;|or|\\+|,|0x"; // 不允许的字符串
		String inj_stra[] = inj_str.split("\\|");
		for (int i = 0; i < inj_stra.length; i++) {
			// 此处使用自写的替换方法 主要特别为可进行对大小写不敏感的替换
			safeString = replace(safeString, inj_stra[i], "[" + inj_stra[i]
					+ "]");
		}
		return safeString;
	}

	/**
	 * 将字符串 source 中的 oldStr 替换为 newStr, 并以大小写敏感方式进行查找
	 * 
	 * @param source
	 *            需要替换的源字符串
	 * @param oldStr
	 *            需要被替换的老字符串
	 * @param newStr
	 *            替换为的新字符串
	 */
	public static String replace(String source, String oldStr, String newStr) {
		return replace(source, oldStr, newStr, false); // 此处设置为大小写不区分的替换
		// 要区分大小写替换请replaceAll函数
	}

	/**
	 * 将字符串 source 中的 oldStr 替换为 newStr, matchCase 为是否设置大小写敏感查找
	 * 
	 * @param source
	 *            需要替换的源字符串
	 * @param oldStr
	 *            需要被替换的老字符串
	 * @param newStr
	 *            替换为的新字符串
	 * @param matchCase
	 *            是否需要按照大小写敏感方式查找
	 */
	public static String replace(String source, String oldStr, String newStr,
			boolean matchCase) {
		if (source == null) {
			return null;
		}
		// 首先检查旧字符串是否存在, 不存在就不进行替换
		if (source.toLowerCase().indexOf(oldStr.toLowerCase()) == -1) {
			return source;
		}
		int findStartPos = 0;
		int a = 0;
		while (a > -1) {
			int b = 0;
			String str1, str2, str3, str4, strA, strB;
			str1 = source;
			str2 = str1.toLowerCase();
			str3 = oldStr;
			str4 = str3.toLowerCase();
			if (matchCase) {
				strA = str1;
				strB = str3;
			} else {
				strA = str2;
				strB = str4;
			}
			a = strA.indexOf(strB, findStartPos);
			if (a > -1) {
				b = oldStr.length();
				findStartPos = a + b;
				StringBuffer bbuf = new StringBuffer(source);
				source = bbuf.replace(a, a + b, newStr) + "";
				// 新的查找开始点位于替换后的字符串的结尾
				findStartPos = findStartPos + newStr.length() - b;
			}
		}
		return source;
	}

	/**
	 * 将字符串编码格式转成GB2312
	 * 
	 * @param str
	 * @return
	 */
	public static String TranEncodeTOGB(String str) {
		try {
			String strEncode = SafeUtil.getEncoding(str);
			String temp = new String(str.getBytes(strEncode), "GB2312");
			return temp;
		} catch (java.io.IOException ex) {

			return null;
		}
	}

	/**
	 * 将字符串编码格式转成UTF8
	 * 
	 * @param str
	 * @return
	 */
	public static String TranEncodeTOUTF(String str) {
		try {
			String strEncode = SafeUtil.getEncoding(str);
			System.out.println("**************TranEncodeTOUTF'Encode:"
					+ strEncode + "***************");
			String temp = new String(str.getBytes(strEncode), "UTF-8");
			return temp;
		} catch (java.io.IOException ex) {

			return null;
		}
	}

	/**
	 * 判断输入字符是否为gb2312的编码格式
	 * 
	 * @param c
	 *            输入字符
	 * @return 如果是gb2312返回真，否则返回假
	 */
	public static boolean isGB2312(char c) {
		Character ch = new Character(c);
		String sCh = ch.toString();
		try {
			byte[] bb = sCh.getBytes("gb2312");
			if (bb.length > 1) {
				return true;
			}
		} catch (java.io.UnsupportedEncodingException ex) {
			return false;
		}
		return false;
	}

	/**
	 * 判断字符串的编码
	 * 
	 * @param str
	 * @return
	 */
	public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s = encode;
				return s;
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) {
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}

	/**
	 * 判断是否为最后当月的最后一天 Lijinyang 20090731
	 * **/
	public static String isMonthEnd() {
		String ret = "";
		Date a = new Date();
		Calendar b = Calendar.getInstance();
		b.setTime(a);
		int lastDay = b.getActualMaximum(Calendar.DAY_OF_MONTH);
		int now = b.get(Calendar.DAY_OF_MONTH);
		if (now == lastDay) {
			ret = "200"; // 是月末 最后一天
		} else {
			ret = "100"; // 是月末 最后一天
		}
		return ret;
	}

	/*
	 * 生成唯一标识流水 Lijinyang 20090731
	 */
	public static String getGUID() {
		String ret = "";
		StringBuffer buf = new StringBuffer();
		Calendar calendar = new GregorianCalendar();
		buf.append(addZero(calendar.get(Calendar.YEAR), 4));
		buf.append(addZero((calendar.get(Calendar.MONTH) + 1), 2));
		buf.append(addZero(calendar.get(Calendar.DAY_OF_MONTH), 2));
		buf.append(addZero(calendar.get(Calendar.HOUR_OF_DAY), 2));
		buf.append(addZero(calendar.get(Calendar.MINUTE), 2));
		buf.append(addZero(calendar.get(Calendar.SECOND), 2));
		buf.append(addZero(calendar.get(Calendar.MILLISECOND), 3));

		ret = buf.toString();

		return ret;

	}

	private static String addZero(int num, int len) {
		StringBuffer s = new StringBuffer();
		s.append(num);
		while (s.length() < len) {
			s.insert(0, "0");
		}
		return s.toString();
	}

	/*
	 * 计算2个时间的时间差
	 */
	public static int getBetweenDayNumber(Date dateA, Date dateB) {
		long dayNumber = 0;
		// 1小时=60分钟=3600秒=3600000
		// long mins = 60L * 1000L;
		long mins = 60L * 1000L;
		// long day= 24L * 60L * 60L * 1000L;计算天数之差

		try {
			java.util.Date d1 = dateA;
			java.util.Date d2 = dateB;
			dayNumber = (d2.getTime() - d1.getTime()) / mins;
		} catch (Exception e) {
			dayNumber = 0;
			e.printStackTrace();
		}
		return (int) dayNumber;
	}

	/*
	 * 计算2个时间的时间差：分钟 ,传入long
	 */
	public static int getBetweenMinsNumber(Long dateA, Long dateB) {
		long dayNumber = 0;
		// 1小时=60分钟=3600秒=3600000
		long mins = 60L * 1000L;
		try {
			java.util.Date d1 = new Date(dateA);
			java.util.Date d2 = new Date(dateB);
			dayNumber = (d2.getTime() - d1.getTime()) / mins;
		} catch (Exception e) {
			dayNumber = 0;
			e.printStackTrace();
		}
		return (int) dayNumber;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
